package com.bianmaba.spring.security.util;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.*;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public final class PasswordEncoderFactory {

    public static Map<String, PasswordEncoder> encoders = new HashMap();

    static {
        encoders.put("bcrypt", new BCryptPasswordEncoder());
        encoders.put("ldap", new LdapShaPasswordEncoder());
        encoders.put("MD4", new Md4PasswordEncoder());
        encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
        encoders.put("noop", NoOpPasswordEncoder.getInstance());
        encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
        encoders.put("scrypt", new SCryptPasswordEncoder());
        encoders.put("SHA-1", new MessageDigestPasswordEncoder("SHA-1"));
        encoders.put("SHA-256", new MessageDigestPasswordEncoder("SHA-256"));
        encoders.put("sha256", new StandardPasswordEncoder());
    }

    public static PasswordEncoder getPasswordEncode(String type) {
        if (type == null) {
            return null;
        }
        Set<Map.Entry<String, PasswordEncoder>> entries = encoders.entrySet();
        for (Map.Entry<String, PasswordEncoder> entry : entries) {
            if (entry.getKey().toLowerCase().equals(type.toLowerCase())) {
                return entry.getValue();
            }
        }
        return null;
    }
}
